<?php
/**
 * Created by PhpStorm.
 * User: wangkk
 * Date: 2019-03-13 11:52
 * Description: {微信卡券基类，主要是获取token和执行curl方法}
*/

namespace app\controllers;
use Yii;
use yii\web\Controller;
//use Memcacheds;

class CommonController extends Controller{
    private $appid;
    private $appsecret;

    public function init()
    {
        $this->appid     = Yii::$app->params['weixin']['appid'];
        $this->appsecret = Yii::$app->params['weixin']['appsecret'];
    }

    /**
     * 获取access_token
     */
    public function get_access_token(){
        //先从缓存获取
        //$test_access_token = Memcacheds::get_cache('test_access_token');
        $test_access_token = Yii::$app->cache->get('test_access_token');
        if($test_access_token){
            return $test_access_token;
        }
        $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appsecret;
        $access_tokenArr = $this->curlget($access_token_url);
        $access_token = $access_tokenArr['access_token'];
        $time = $access_tokenArr['expires_in'];
        //获取到access_token保存到缓存
        //Memcacheds::set_cache('test_access_token', $access_token, $time-100);
        Yii::$app->cache->set('test_access_token', $access_token, $time-100);
        return $access_token;
    }

    /*
     * curl get请求
     * @param  string $url 请求地址
     * @return array  请求返回的数据，数组格式
     */
    public function curlget($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

    /*
     * curl post请求
     * @param   string  $url         请求地址
     * @param   array   $post_data   post数据
     * @return  array   返回的数据
     */
    public function curlpost($url = '', $post_data = array()) {
        if (empty($url) || empty($post_data)) {
            return false;
        }
        $o = "";
        foreach ( $post_data as $k => $v ) {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return json_decode($data, true);
    }

    /*
     * curl post请求
     * @param   string  $url  请求地址
     * @param   array   $data 请求数据
     * @param   bool    $json 是否为json请求
     * @return  array   返回的数据
     */
    public function curlpostJson($url, $data = NULL, $json = false){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!empty($data)) {
            if($json && is_array($data)){
                $data = json_encode( $data,JSON_UNESCAPED_UNICODE );    //注意：json序列化时添加参数JSON_UNESCAPED_UNICODE，否则中文出问题
            }
            //var_dump($data);exit;
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            if($json){ //发送JSON数据
                curl_setopt($curl, CURLOPT_HEADER, 0);
                curl_setopt($curl, CURLOPT_HTTPHEADER,
                    array(
                        'Content-Type: application/json; charset=utf-8',
                        'Content-Length:' . strlen($data))
                );
            }
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if($errorno) {
            return array('errorno' => false, 'errmsg' => $errorno);
        }
        curl_close($curl);
        return json_decode($res, true);
    }

    /*
     * 处理多维数组中的空值
     * @param   array  $arr  多维数组
     * @return  array  $arr  去掉空值后的多维数组
     */
    public function array_filter_recursive(array &$arr){
        if (empty($arr)) {
            return [];
        }
        foreach ($arr as $k => $v) {
            if (is_array($v)) {
                $arr[$k] = $this->array_filter_recursive($v);
            }
            //$v == false不清除
            if($v === '' || $v === null){
                unset($arr[$k]);
            }
        }
        return $arr;
    }
    //打印数据
    public function dump($data){
        echo '<pre>';
        print_r($data);
    }
}